/*
 * ADRIAN - A 3D role playing game
 * Copyright (C) 2009  Bhanu Chetlapalli, Vamsi Krishna
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */


#include "TextObject.h"

TextObject::TextObject(TTFFont *font, GLuint tid)
{
	str = NULL;
	len = 0;

	texid = tid;
	if (texid == INVALID_TEXTURE_ID)
		glGenTextures(1, &texid);

	this->font = font;
	setColor(1.0, 1.0, 1.0);
	dirty = true;

	tx = ty = 1.0;
}

TextObject::~TextObject()
{
	if (str)
		free(str);
	if (glIsTexture(texid))
		glDeleteTextures(1, &texid);
}

void TextObject::setColor(int red, int green, int blue)
{
    color[0] = red/255.0;
    color[1] = green/255.0;
    color[2] = blue/255.0;
    color[3] = 1;
}
/*void TextObject::setColor(float red, float green, float blue)
{
    color[0] = red;
    color[1] = green;
    color[2] = blue;
    color[3] = 1;
}*/

void TextObject::drawText(float x, float y)
{
    glColor4fv(color);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
   // glEnable(GL_ALPHA_TEST);
   // glAlphaFunc(GL_GREATER, 0.5);
    glBindTexture(GL_TEXTURE_2D, texid);
    glBegin(GL_POLYGON);
    glTexCoord2f(0, ty);
    glVertex2f(x, y-h);
    glTexCoord2f(tx, ty);
    glVertex2f(x + w, y-h);
    glTexCoord2f(tx, 0);
    glVertex2f(x + w, y);
    glTexCoord2f(0, 0);
    glVertex2f(x, y);
    glEnd();
    glDisable(GL_BLEND);
   // glDisable(GL_ALPHA_TEST);
    glColor4f(1, 1, 1, 1);
}

void TextObject::setText(const char *s)
{
	if (s) {
        font->getTextSize(s, &w, &h);
		/* Same text - do nothing */
		if (str && !strcmp(str, s))
			return;

		if (str)
			delete []str;

        if (glIsTexture(texid))
			glDeleteTextures(1, &texid);

	    glGenTextures(1, &texid);

		len = strlen(s) + 1;
		str = new char[len];
		strcpy(str, s);
        SDL_Color col;
        col.r = 255;
        col.g = 255;
        col.b = 255;
		font->createTexture(texid, str, &col, &tx, &ty);
		dirty = false;
	}
}

